﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DataBaseLayer;
using CommonLayer;

namespace TSUILayer.Views.Sales
{
    /// <summary>
    /// Interaction logic for JobCardAView.xaml
    /// </summary>
    public partial class JobCardAView : Page
    {
        DataLayer data = null;
        JOB_CARD jobCard = new JOB_CARD() { SALES_INVOICE = new SALES_INVOICE() };
        IEnumerable<DDBinding> _autoSource = null;
        JobCardBView jobBInstance = null;
        static JobCardAView jobCardAInstance = null;
        #region - UI Validations.
        private void NumericOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = IsTextNumeric(e.Text);
        }
        private static bool IsTextNumeric(string str)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
            return reg.IsMatch(str);

        }


        private void AlphabetOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = IsAlphabet(e.Text);
        }
        private static bool IsAlphabet(string str)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^A-Za-z]");
            return reg.IsMatch(str);
        }


        private void FloatingPointOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = IsFloatingPointvalue(e.Text);
        }
        private static bool IsFloatingPointvalue(string str)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9.-]");
            return reg.IsMatch(str);
        }


        private void AlphaNumerictOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = IsAlphaNumeric(e.Text);
        }
        private static bool IsAlphaNumeric(string str)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]");
            return reg.IsMatch(str);
        }
        #endregion - UI Validations.

        public JobCardAView()
        {
            InitializeComponent();
            data = DataLayer.Instance;
            jobCardAInstance = this;
            _autoSource = data.GetAll<DELIVERY_CHALAN>(s => !s.IS_DC).Select(s => new DDBinding() { Id = s.TRACTOR_ID, Name = s.TRACTOR_PURCHASE.TRACTOR_ENGINE_NO });
            cmbCustomer.ItemsSource = data.GetAllCustomers();
        }

        private void btnAddComplaint_Click(object sender, RoutedEventArgs e)
        {
            JOB_COMPLAINT complaint = new JOB_COMPLAINT();
            complaint.ACTION_TAKEN = txtActionOnComplaint.Text;
            complaint.ACTUAL_COMPLAINT = txtComplaint.Text;
            complaint.LABOUR_CHARGES = Convert.ToDecimal(txtLabourEstimation.Text);
            jobCard.JOB_COMPLAINTs.Add(complaint);
            gridComplaint.ItemsSource = jobCard.JOB_COMPLAINTs.Select((s, i) => new { SlNo = ++i, Complaint = s.ACTUAL_COMPLAINT, Action = s.ACTION_TAKEN, Charge = s.LABOUR_CHARGES }).ToList();
            txtActionOnComplaint.Clear();
            txtComplaint.Clear();
            txtLabourEstimation.Clear();
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            string tractorApp = string.Empty;
            TractorAppGrid.Children.OfType<CheckBox>().Where(s => s.IsChecked ?? false).All(s => { tractorApp += s.Content.ToString() + ","; return true; });
            jobCard.SERIAL_NUMBER = Convert.ToInt32(txtJobCardSerialNo.Text);
            jobCard.ESTIMATED_COST = Convert.ToDecimal(txtEstimatedCost.Text);
            jobCard.SERVICE_COUPON_NO = string.IsNullOrEmpty(txtServiceCouponNo.Text) ? default(int) : Convert.ToInt32(txtServiceCouponNo.Text);
            jobCard.TRACTOR_APPLICATION = tractorApp.Remove(tractorApp.Length - 1);
            jobCard.IS_ACCEDENTAL = chkAccidental.IsChecked;
            jobCard.IS_MOBILESERVICE = chkMobileService.IsChecked;
            jobCard.IS_PAID = chkPaid.IsChecked;
            jobCard.IS_SERVICECLINIC = chkServiceClinic.IsChecked;
            jobCard.ESTIMATED_DELIVERY = dateEsimatedDelivery.SelectedDate;
            jobCard.DATETIME_IN = dateTimeIn.SelectedDate;
            jobCard.SERVICE_STARTDATETIME = dateTimeServiceStart.SelectedDate;
            jobCard.SERVICE_ENDDATETIME = dateTimeServiceFinish.SelectedDate;
            jobCard.REPEAT_FIR_DETAIL = txtRepeat_PreviousFIRDetail.Text;
            jobCard.REGISTRATION_NO = txtRegistrtionNo.Text;
            if (!chkEnggSearch.IsChecked.Value)
            {
                jobCard.JOB_TRACTOR_CUSTOMER = new JOB_TRACTOR_CUSTOMER()
                {
                    CHASSIS_NO = txtChassisNo.Text,
                    CUSTOMER_ID = 1,
                    DATEOF_INSTALLATION = dtPickDOI.SelectedDate,
                    ENGINE_NO = txtEngineNo.Text,
                    MODEL = txtTractorModel.Text,
                    PDI_HOURS = Convert.ToDecimal(txtPdiHrs.Text)
                };
            }

            this.NavigationService.LoadCompleted += NavigationService_LoadCompleted;
            if (this.NavigationService.CanGoForward)
                this.NavigationService.GoForward();
            else
                this.NavigationService.Navigate(new JobCardBView(ref jobBInstance, data));

        }

        void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
        {
            if (jobBInstance != null)
                jobBInstance.UpdateJobCardBView(ref jobCardAInstance);
        }

        public JOB_CARD GetObj()
        {
            return jobCard;
        }

        private void txtEngineNoForSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_autoSource != null)
            {
                var result = _autoSource.Where(s => s.Name.ToLower().Contains(txtEngineNoForSearch.Text.ToLower()) && !string.IsNullOrEmpty(txtEngineNoForSearch.Text)).Select(s => s);
                lstSugesstions.Visibility = result.Count() <= 0 ? Visibility.Collapsed : Visibility.Visible;
                lstSugesstions.ItemsSource = result;
            }
        }

        private void lstSugesstions_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            txtEngineNoForSearch.TextChanged -= new TextChangedEventHandler(txtEngineNoForSearch_TextChanged);
            if (lstSugesstions.SelectedValue != null)
            {
                txtEngineNoForSearch.Text = (lstSugesstions.SelectedItem as DDBinding).Name;
                var result = data.GetById<DELIVERY_CHALAN>(s => s.TRACTOR_ID == Convert.ToInt32(lstSugesstions.SelectedValue));

                if (result != null)
                {
                    jobCard.TRACTOR_ID = result.TRACTOR_ID;
                    jobCard.JOBTRACTOR_ID = null;
                    jobCard.SALES_INVOICE.CUSTOMER = result.CUSTOMER;
                    jobCard.SALES_INVOICE.SELL_TYPE = data.GetMasterId(CommonLayer.SPARETYPE.ITEMS.ToString());
                    jobCard.SALES_INVOICE.INVOICE_DATE = dateOfJobCard.SelectedDate.Value;
                    txtEngineNo.Text = result.TRACTOR_PURCHASE.TRACTOR_ENGINE_NO;
                    txtChassisNo.Text = result.TRACTOR_PURCHASE.TRACTOR_CHASSIS_NO;
                    txtTractorModel.Text = result.TRACTOR_PURCHASE.TRACTOR_MODEL.TRACTOR_MODEL_NAME;
                    txtPdiHrs.Text = Convert.ToString(result.TRACTOR_PURCHASE.TRACTOR_PDI_HOURS);
                    cmbCustomer.Text = result.CUSTOMER.CUSTOMER_NAME;
                    txtCustContactNo.Text = result.CUSTOMER.CONTACT_NO_1.ToString();
                    txtCustAddress.Text = result.CUSTOMER.CUSTOMER_ADDRESS;
                    dtPickDOI.SelectedDate = result.SALES_INVOICE.INVOICE_DATE.Value;
                }
            }
            txtEngineNoForSearch.Clear();
            lstSugesstions.Visibility = Visibility.Collapsed;            
            txtEngineNoForSearch.TextChanged += new TextChangedEventHandler(txtEngineNoForSearch_TextChanged);
        }

        private void chkPaid_Click(object sender, RoutedEventArgs e)
        {
            txtServiceCouponNo.IsEnabled = chkPaid.IsChecked.Value ? false : true;
            txtServiceCouponNo.Clear();
        }

        private void chkEnggSearch_Click(object sender, RoutedEventArgs e)
        {
            txtEngineNoForSearch.IsEnabled = chkEnggSearch.IsChecked.Value;
            EnableDisableControls(gbTractorDetails, !chkEnggSearch.IsChecked.Value);
            EnableDisableControls(grdCustomerDetails, !chkEnggSearch.IsChecked.Value, true);
        }

        private void EnableDisableControls(Grid srcGrid, bool isEnabled, bool checkExtened = false)
        {
            srcGrid.Children.OfType<TextBox>().All(s => { s.IsEnabled = isEnabled; s.Clear(); return true; });
            cmbCustomer.IsEnabled = isEnabled;
            cmbCustomer.SelectedIndex = -1;
            if (checkExtened)
            {
                chkOwnerDriven.IsEnabled = dtPickDOI.IsEnabled = isEnabled;
                chkOwnerDriven.IsChecked = false;
                dtPickDOI.SelectedDate = null;
            }
        }
    }
}
